package top.jiangqiang.qyblog.core.util;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import top.jiangqiang.qyblog.core.domain.entity.AdminUser;

import java.util.List;

/**
 * @author JiangQiang
 */
public class SessionUtil {
    public static <V> void set(String key, V value) {
        SaSession session = StpUtil.getSession();
        session.set(key, value);
    }

    @SuppressWarnings("unchecked")
    public static <V> V get(String key) {
        SaSession session = StpUtil.getSession();
        return (V) session.get(key);
    }

    /**
     * @return 获取当前用户信息
     */
    public static AdminUser getUser() {
        return get(SaSession.USER);
    }

    /**
     * @return 将当前登录用户的信息存入session
     */
    public static void setUser(AdminUser adminUser) {
        set(SaSession.USER, adminUser);
    }

    /**
     * @return 获取当前用户id 没有登录会抛出异常
     */
    public static Long getUserId() {
        return StpUtil.getLoginIdAsLong();
    }

    /**
     * 获取当前用户id，没有登录不会抛出异常
     *
     * @return
     */
    public static Long getUserIdDefaultNull() {
        try {
            return getUserId();
        } catch (Exception e) {
            return null;
        }
    }

    public static AdminUser getRoles() {
        return get(SaSession.ROLE_LIST);
    }

    public static void setRoles(List<?> roles) {
        set(SaSession.ROLE_LIST, roles);
    }

    public static AdminUser getPermissions() {
        return get(SaSession.PERMISSION_LIST);
    }

    public static void setPermissions(List<?> permissions) {
        set(SaSession.PERMISSION_LIST, permissions);
    }
}
